package com.itany.cloud.controller;

import com.itany.cloud.config.RestTemplateConfig;
import com.itany.cloud.entity.User;
import com.itany.cloud.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

/**
 * @author 石小俊
 */
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${provider-server.users-url}")
    private String serverUrl;


    @GetMapping("/{id}")
    public ResponseResult findById(@PathVariable Integer id) {
        return restTemplate.getForObject(serverUrl + "/users/{id}", ResponseResult.class, id);
    }

    @GetMapping
    public ResponseResult findAll() {
        return restTemplate.getForObject(serverUrl + "/users", ResponseResult.class);
    }

    @PostMapping
    public ResponseResult addUser(User user) {
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("username", user.getUsername());
        params.add("password", user.getPassword());
        return restTemplate.postForObject(serverUrl + "/users", params, ResponseResult.class);
    }

    @PutMapping
    public ResponseResult modifyUser(User user) {
        String url = new StringBuffer()
                .append(serverUrl)
                .append("/users?id={id}")
                .append("&username={username}")
                .append("&password={password}")
                .toString();
        ResponseEntity<ResponseResult> responseEntity = restTemplate.exchange(url, HttpMethod.PUT, null, ResponseResult.class, user.getId(), user.getUsername(), user.getPassword());
        return responseEntity.getBody();
    }

    @DeleteMapping("/{id}")
    public ResponseResult deleteById(@PathVariable Integer id) {
        ResponseEntity<ResponseResult> responseEntity = restTemplate.exchange(serverUrl + "/users/{id}", HttpMethod.DELETE, null, ResponseResult.class, id);
        return responseEntity.getBody();
    }

}
